/**
 * Created by gaojun on 17-3-7.
 */
import mqtt from 'mqtt';
import config from '../config';
import { Message } from '../helps/message';
import * as appAuthController from '../controllers/app/auth';
import * as appRobotController from '../controllers/app/robot';
import * as robotModel from '../models/robot';
import * as userChatModel from '../models/user_chat';


function sendRobot(socket, event, message) {
  let { user, robot } = socket;
  if (!user) socket.emit('error', 'user is empty');
  if (!robot) socket.emit('error', 'robot is empty');
  message = message || {};
  message.event = event;
  message.uid = user.id;
  socket.mqtt.publish(`robot/${robot.id}`, JSON.stringify(message));
}

const base = new Message('/', {
  * connect({ token }) {
    if (!token) {
      this.disconnect(true);
      return;
    }

    // 验证token
    try {
      this.user = yield appAuthController.validToken({ token });
      let robot_id = yield appRobotController.getRobotId({ user_id: this.user.id });
      if (robot_id) {
        this.robot = yield appRobotController.getInfo({ robot_id });
      }
    } catch (e) {
      this.disconnect(true);
      return;
    }

    // 建立mqtt链接, 绑定app自身topic
    this.mqtt = mqtt.connect(config.mqtt);
    this.mqtt.on('connect', () => {
      this.mqtt.subscribe(`app/${this.user.id}`);
    });
    this.mqtt.on('message', (topic, message) => {
      let info = JSON.parse(message.toString());
      if (!info.event) return;
      if (!info.rid) return;
      let handle = null;
      switch (info.event) {
        case 'chat_sound':
          // 发送语音
          // 记录
          handle = userChatModel.add({
            robot_id: info.rid,
            user_id: this.user.id,
            type: 3,
            feature: 2,
            direction: 1,
            content: JSON.stringify({
              url: info.url,
              duration: info.duration,
            }),
          });
          break;
        case 'sync_sound':
          // 同步播放
          handle = Promise.resolve();
          break;
        case 'upgrade':
          // 升级
          handle = Promise.resolve();
          break;
        case 'alive':
          // 存活通知
          // 更新数据库状态
          handle = robotModel.put(info.rid, { alive_time: new Date() });
          break;
        default:
          return;
      }
      // 通知到客户端
      handle.then(() => {
        this.emit(info.event, info);
      });
    });
  },
  * disconnect() {
    // console.log('base disconnect');
  },
  * disconnecting() {
    // console.log('base disconnecting');
  },
});

// 无需处理业务逻辑的事件
base.event('robot', function* ({ event, message }) {
  // alive, set_night, close_night, set_anti_addiction, close_anti_addiction, play_sound, add_book
  sendRobot(this.mqtt, this.robot.id, this.user.id, event, message);
});

base.event('bind', function* ({ rid }) {
  // 绑定机器人
  this.robot = { id: rid };
  sendRobot(this, 'bind');
});

base.event('unbind', function* () {
  // 解绑机器人
  sendRobot(this, 'unbind');
  this.robot = {};
});

base.event('chat_text', function* ({ message }) {
  // 文字聊天, 记录
  yield userChatModel.add({
    robot_id: this.robot.id,
    user_id: this.user.id,
    type: 1,
    feature: 1,
    direction: 2,
    content: JSON.stringify({
      message,
    }),
  });
  sendRobot(this, 'chat_text', { message });
});

base.event('chat_face', function* ({ face }) {
  // 表情聊天, 记录
  yield userChatModel.add({
    robot_id: this.robot.id,
    user_id: this.user.id,
    type: 2,
    feature: 1,
    direction: 2,
    content: JSON.stringify({
      face,
    }),
  });
  sendRobot(this, 'chat_face', { face });
});

base.event('chat_sound', function* ({ url, duration }) {
  // 语音聊天, 记录
  yield userChatModel.add({
    robot_id: this.robot.id,
    user_id: this.user.id,
    type: 3,
    feature: 2,
    direction: 2,
    content: JSON.stringify({
      url,
      duration,
    }),
  });
  sendRobot(this, 'chat_face', { url, duration });
});

export default base;
